/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package p2p.raca.Server;


import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.*;
import java.net.Socket;

/**
 *
 * @author p
 */
public class ServerFileSender extends Thread {
    
    private ServerSocket servsock = null;
    private Socket sock;
    String hostname;
    int size;
    int port;
    public ServerFileSender()
    {
         try {
            servsock = new ServerSocket(5051);
        } catch (IOException ex) {
        }
        hostname = servsock.getInetAddress().getHostName();
    }
    
  
    private void sendFile(String fileName) throws IOException
    {
         // create socket

      Socket sok = servsock.accept();
      int offset=0;
      // sendfile
      File myFile = new File (fileName);
      
      byte [] mybytearray  = new byte [1024];
      
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      OutputStream os = sok.getOutputStream();
      
        long start = System.nanoTime();
          while (offset < (int)myFile.length())
          {
               int byteread = bis.read(mybytearray,0,1024);
                  os.write(mybytearray,0,byteread);
                  os.flush();
                  offset+=byteread;
                  offset = offset + 1024;
          }
          
          long elapsedTime = System.nanoTime() - start;
          System.out.println("Tempo gasto para enviar o arquivo: "+ myFile.getName()+ " foi: " + elapsedTime);
      
      sok.close();
      servsock.close();
    }
    public void sendMessage()
    {
        try {  
         Socket clientSocket = new Socket(hostname, port);  
  
 
         DataOutputStream toServer = new DataOutputStream(clientSocket.getOutputStream());  
         DataInputStream fromServer = new DataInputStream(clientSocket.getInputStream());
         //close socket 
         size = fromServer.read();
         
         toServer.close();
         clientSocket.close();
         
      } catch (Exception e) {  
      }  

    }
    @Override
    public void run()
    {
        try {
            sendFile(ServerRequestHandler.name);
        } catch (IOException ex) {
        }
    }
    
}
